package com.tuling.netty.base;

import io.netty.util.HashedWheelTimer;
import io.netty.util.Timeout;
import io.netty.util.TimerTask;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;

/**
 * 时间轮算法
 */
public class TimingWheel {
    public static void main(String[] args) throws InterruptedException {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        HashedWheelTimer timer = new HashedWheelTimer(r -> new Thread(r, "HashedWheelTimer " + r.hashCode()), 1, TimeUnit.MILLISECONDS, 8);

        System.out.println("当前时间:" + LocalDateTime.now().format(formatter));
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run(Timeout timeout) {
                System.out.println("hello world " + LocalDateTime.now().format(formatter));
                // 执行完之后再次加入调度
                timer.newTimeout(this, 4, TimeUnit.SECONDS);
            }
        };
        // 将定时任务放入时间轮
        timer.newTimeout(timerTask, 4, TimeUnit.SECONDS);
        Thread.currentThread().join();
    }
}
